import { Suspense, useEffect, useState } from 'react'
import { Stats, useProgress } from '@react-three/drei'
import { Canvas } from '@react-three/fiber'
import type { FC, ReactNode } from 'react'
import { Spin } from 'antd'

interface SceneManagerProps {
  children: ReactNode
  showStats?: boolean
  showSpinner?: boolean
}

const LoadingSpinner: FC = () => {
  const { progress } = useProgress()
  return (
    <div style={{ 
      position: 'absolute', 
      top: '50%', 
      left: '50%', 
      transform: 'translate(-50%, -50%)'
    }}>
      <Spin tip={`Loading... ${Math.round(progress)}%`} size="large" />
    </div>
  )
}

const ErrorBoundary: FC<{ children: ReactNode }> = ({ children }) => {
  const [hasError, setHasError] = useState(false)

  useEffect(() => {
    const handleError = () => setHasError(true)
    window.addEventListener('error', handleError)
    return () => window.removeEventListener('error', handleError)
  }, [])

  if (hasError) {
    return (
      <div style={{ 
        position: 'absolute', 
        top: '50%', 
        left: '50%', 
        transform: 'translate(-50%, -50%)',
        color: 'red' 
      }}>
        An error occurred while rendering the 3D scene.
        Please refresh the page or contact support if the issue persists.
      </div>
    )
  }

  return <>{children}</>
}

const SceneManager: FC<SceneManagerProps> = ({ 
  children, 
  showStats = false,
  showSpinner = true 
}) => {
  return (
    <div style={{ position: 'relative', width: '100%', height: '100%' }}>
      <ErrorBoundary>
        <Canvas
          camera={{ position: [0, 0, 5], fov: 75 }}
          style={{ background: '#f0f0f0' }}
          shadows
          dpr={[1, 2]} // Responsive pixel ratio
          performance={{ min: 0.5 }} // Performance optimization
        >
          {showStats && <Stats />}
          <Suspense fallback={null}>
            {children}
          </Suspense>
        </Canvas>
        {showSpinner && <LoadingSpinner />}
      </ErrorBoundary>
    </div>
  )
}

export default SceneManager 